package com.mg.upload.service.impl;

import com.mg.upload.entity.VideoManage;
import com.mg.upload.entity.VideoUpload;
import com.mg.upload.mapper.VideoManageMapper;
import com.mg.upload.mapper.VideoUploadMapper;
import com.mg.upload.service.VideoUploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Service
public class VideoUploadServiceImpl implements VideoUploadService {

    private String newPath;

    @Resource
    VideoUploadMapper videoUploadMapper;

    @Resource
    VideoManageMapper videoManageMapper;

    /**
     * 创建文件夹，并将传过来的文件保存
     * .class.getResource: 获取类绝对路径
     * randomUUID(): 获取随机的UUID
     * MultipartFile(可单个)，MultipartFile[](可多个)
     * getOriginalFilename(): 获取原文件名
     * transferTo(): 将文件写入
     * @param files 传输过来的文件
     * @return 若执行完所有语句则返回1
     * @throws IOException
     */
    @Override
    public int uploadVideo(MultipartFile files)throws IOException{
        //String path = VideoUploadServiceImpl.class.getResource("").toString().substring(6, 81);
        String path = VideoUploadServiceImpl.class.getResource("").toString().substring(6, 66);
        String suffix = files.getOriginalFilename().substring(files.getOriginalFilename().lastIndexOf("."));
        String videoPath=UUID.randomUUID().toString()+suffix;
        File file = new File(path+"/src/main/resources/Upload/"+videoPath);
        if (!file.exists()){
            file.mkdirs();
        }
        files.transferTo(file);
        newPath="mg-video-manage/video-upload/src/main/resources/Upload"+videoPath;
        return 1;
    }

    /**
     * 获取传输文件的相关信息
     * 并对视频基础信息表，和视频管理表进行添加
     * @param videoUpload 传过来的文件的信息
     * @return 成功则返回1，失败则返回0
     */
    @Override
    public int setVideo(VideoUpload videoUpload){
        VideoManage videoManage = new VideoManage();
        //当视频未提交时直接返回，不用进行其他操作
        if (newPath==null){
            return 0;
        }
        videoManage.setId(0);
        videoManage.setComNumber(0);
        videoManage.setLikes(0);
        videoManage.setForward(0);
        videoManage.setFavorites(0);
        videoUpload.setAddress(newPath);
        int insert = videoUploadMapper.insert(videoUpload);
        videoManage.setName(videoUpload.getName());
        int insert1 = videoManageMapper.insert(videoManage);
        return insert==insert1&&insert==1?insert:0;
    }

    /**
     * 逻辑删除视频，并对其副表进行逻辑删除
     * @param id 通过id删除
     * @return
     */
    @Override
    public int remove(int id){
        VideoUpload videoUpload = videoUploadMapper.selectById(id);
        String name = videoUpload.getName();
        int i = videoUploadMapper.deleteById(id);
        int remove = videoManageMapper.remove(name);
          return i==remove&&i==1?i:0;
    }
}
